//
//  SHHomeViewController.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/19.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit

private let homeCellId = "homeCellId"
class SHHomeViewController: SHVisitorViewController {

    
    lazy var statusListViewModel:SHStatusListViewModel = SHStatusListViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()

        if !isLogin {
            
            visitorView?.setupVisitorViewInfo(nil, title: nil)
            
            return
        }
        setupTableViewInfo()
        getHomeData()
    }
    
   func setupTableViewInfo(){
    
    //添加到导航控制器的bar中
    
    navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
    
    // 设置数据源代理
    tableView.dataSource = self
    
    tableView.delegate = self
    // 注册cell
    tableView.registerClass(SHStautsCell.self, forCellReuseIdentifier: homeCellId)
    // 设置tableView 的cell的预估行高 (预估行高越接近真实cell高度越好)
    tableView.estimatedRowHeight = 200
     tableView.separatorStyle = .None
    tableView.tableFooterView = indicatorView
    
    tableView.addSubview(refreshControl)
    
    refreshControl.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
    
    }
    
    func refreshAction(){
        
        getHomeData()
        
    }
    
    //懒加载控件
    private lazy var indicatorView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = ThemeColor
        return view
    }()
    
    
    //懒加载刷新控件
    private lazy var refreshControl: SHRefreshControl = SHRefreshControl()
    //懒加载刷新数据显示栏
    private lazy var pullDownTipLabel: UILabel = {
        let lab = UILabel(textColor: UIColor.whiteColor(), textFont: 12)
//        lab.frame = CGRectMake(0, 30, SCREENW, 30)
        lab.frame = CGRect(x: 0, y: 64 - 30, width: SCREENW, height: 30)
        lab.textAlignment = .Center
        
        lab.backgroundColor = ThemeColor
        
        lab.hidden = true
        
        return lab
        
    }()

}

extension SHHomeViewController:UITableViewDataSource,UITableViewDelegate{
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusListViewModel.statusList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCellId, forIndexPath: indexPath) as! SHStautsCell
        
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        
        return cell
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == self.statusListViewModel.statusList.count - 1 && !indicatorView.isAnimating(){
            
            indicatorView.startAnimating()
            getHomeData()
        }
    }
    
}

extension SHHomeViewController{
    
    func getHomeData(){
        statusListViewModel.loadHomeData(indicatorView.isAnimating()) { (isSuccess,count) -> () in
            //停止动画
            self.endRefreshing()
          
            if !isSuccess{
                
                print("请求失败")
                
                return
            }
            //刷新数据
            
            self.tableView.reloadData()
            // 下拉刷新
            if count >= 0 {
                
                self.setpullDownTipLabelAnim(count)
            }
        }
    }
     // 停止各种动画
    func endRefreshing(){
        
        self.indicatorView.stopAnimating()
        
        self.refreshControl.endRefreshing()
        
    }
    
    func setpullDownTipLabelAnim(count: Int){
        
        if pullDownTipLabel.hidden == false{
            
            return
        }
        
        pullDownTipLabel.hidden = false
        
        var name = ""
        
        if count == 0 {
            name = "已经是最新的微博数据了"
        }else{
            
            name = "已加载了\(count)条微博"
        }
        
        pullDownTipLabel.text = name
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, 30)
            }) { (_) -> Void in
                
              UIView.animateKeyframesWithDuration(0.5, delay: 1, options: [], animations: { () -> Void in
                  self.pullDownTipLabel.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                    
                    self.pullDownTipLabel.hidden = true
              })
        }
    }
    
}


